package it.polito.let.http;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.logging.Logger;


public class HTTPError extends Exception {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6653812163828610201L;

	private static final String PAGE_START = "<html>\n<head>\n<title>";

	private static final String PAGE_HEADER_END = "</title>\n</head>\n<body>\n<h1>";

	private static final String PAGE_HEADING_END = "</h1>\n";

	private static final String PAGE_BETWEEN_START = "<pre>";

	private static final String PAGE_BETWEEN_END = "</pre>\n";

	private static final String PAGE_END  = "</body>\n</html>\n";

	private Response response;

	private String responsePayload = PAGE_START;

	public HTTPError(Short responseCode, String responseMessage) {
		response = new Response("HTTP/1.1", responseCode, responseMessage);

		if(responseCode < 200) {
			responsePayload += "Information";
		} else if(responseCode < 300) {
			responsePayload += "Successful";
		} else if(responseCode < 400) {
			responsePayload += "Redirection";
		} else if(responseCode < 500) {
			responsePayload += "Client Error";
		} else {
			responsePayload += "Server Error";
		}

		responsePayload += PAGE_HEADER_END;
		responsePayload += responseCode + " " + responseMessage + PAGE_HEADING_END;
		Logger.getLogger("it.polito.let.jhpserver").warning("HTTP Server: HTTP Error thrown. Code: "+responseCode+" Message: "+responseMessage);
	}

	public void addAdditionalInfo(String info) {
		responsePayload += PAGE_BETWEEN_START + info + PAGE_BETWEEN_END;
	}

	public void addHeader(String fieldName, String fieldValue) throws HTTPError {
		response.setHeaderField(fieldName, Header.parseHeader(fieldValue));
	}

	public Response getResponse() {
		byte[] buf = (responsePayload + PAGE_END).getBytes();
		InputStream payloadStream = new ByteArrayInputStream(buf);

		try {
			response.setHeaderField("Content-Length", Header.parseHeader(String.valueOf(buf.length)));
			response.setPayloadStream(payloadStream);
		} catch(HTTPError e) {
		}

		return response;
	}
}